// 切换医院时在SOCKET这里修改ws地址
const Consultation_SOCKET = `wss://${domain}/consultation`

if ("".trim === undefined) {
    String.prototype.trim = function () {
        return this.replace(/(^\s*)|(\s*$)/g, "");
    }
    String.prototype.ltrim = function () {
        return this.replace(/(^\s*)/g, "");
    }
    String.prototype.rtrim = function () {
        return this.replace(/(\s*$)/g, "");
    }
}
/**
 * TODO: 会诊websocket配置
 * @type {{}}
 */
var isInvited = false
var consultationSocketConfig = {}
// 处理会诊开始
function handleConsultationStart(res) {
    consultationSocketConfig.room = res.roomId + ''
    sessionStorage.setItem('cTencentConfig',  jsonToStr({
        room: res.roomId + '',
        ...(res.configuration || {})
    }))
    // 判断当前页面地址
    const currentPagePath= location.href
    //判断页面类型
    console.log('currentPagePath',currentPagePath)
    if(currentPagePath.includes("consult_chat.htm")){
        console.log("当前页面是会诊页");
        return
    }
    if (isInvited) {
        return;
    }
    isInvited = true
   // 去往会诊页面  url: `/pages/chat/consult_chat/consult_chat?logId=${res.roomId}`
    goPage(`consult_chat.htm?logId=${res.roomId}`)
}
// 处理会诊结束
function handleConsultationEnd() {
    msgInfo('会诊结束');
    // 返回上一级页面，如果不存在返回首页
    goPageNo(-1);
}


var consultationSocket = {
    heartbeatTime: 8000,  // 心跳时间
    wsUrl: "",
    token: "",
    ws: {},
    intervalId: 0,  // 心跳定时器id
    lock: false,
    initWebSocket: function (wsUrl, token) {
        if (wsUrl) {
            this.wsUrl = wsUrl;
        }
        if (token) {
            this.token = token;
        }
        var that = this;
        this.ws = new WebSocket(this.wsUrl);
        this.ws.onopen = this.onOpen.bind(this);
        this.ws.onmessage = function (event) {
            if (typeof event.data === 'string') {
                let content = event.data;
                if (content.indexOf('{') === 0) {
                    content = JSON.parse(content);
                    console.log('消息事件', that.onMessage);
                    that.onMessage(content);
                }
            }
        };
        this.ws.onclose = this.onClose.bind(this);
        this.ws.onerror = this.onError.bind(this);
    },
    onOpen: function (event) {
        this.login();
        this.resetHeartbeat();
    },
    onMessage: function (msg) {
        console.log(msg, '收到消息')
    },
    onClose: function (evt) {
        console.log("Connection closed.");
        if (evt.code !== 1000) {
            this.reconnect();
        }
    },
    onError: function (ev) {
        this.reconnect();
    },
    login: function () {
        // 进行登录认证
        this.send(1, { token: this.token });
    },
    reconnect: function () {
        if (this.lock) {
            return;
        }
        this.lock = true;
        var that = this;
        this.intervalId = setTimeout(function () {
            that.initWebSocket();
            that.lock = false;
        }, 3000);
    },
    startWsHeartbeat: function () {
        var that = this;
        this.intervalId = setInterval(function () {
            //判断websocket当前状态
            // 0 ：对应常量 正在建立连接连接，还没有完成。
            // 1 ：对应常量OPEN   连接成功建立，可以进行通信。
            // 2 ：对应常量CLOSING  连接正在进行关闭握手，即将关闭。
            // 3 : 对应常量CLOSED  连接已经关闭或者根本没有建立。
            if (that.ws.readyState === 1) {
                that.ws.send("ping"); // 心跳包
            } else if (3 === that.ws.readyState) {
                that.reconnect();
            }
        }, this.heartbeatTime);
    },
    resetHeartbeat: function () {
        this.intervalId > 0 && clearInterval(this.intervalId);
        this.startWsHeartbeat()
    },
    /**
     *
     * @param type 信息包类型
     * @param data 发送的需要发送的数据
     */
    send: function (type, data) {
        if (!data) {
            data = {};
        }
        data.packageType = type;
        if (this.ws.readyState !== 1) {
            return;
        }
        console.log('------- 远程会诊发送数据', type, data);
        data = JSON.stringify(data);
        this.ws.send(data);
    }
};

//初始化webscoket
// function initWebSocket() {
// 连接socket 重构的聊天要用到socket
var consultationToken = null;
var consultationUserJson = localStorage.getItem('DSXBuserJson');
if (consultationUserJson) {
    user_id = strToJson(consultationUserJson).id
    consultationToken = strToJson(consultationUserJson).h5Token

    // 连接socket
    consultationSocket.initWebSocket(Consultation_SOCKET, consultationToken);
}

